﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Util;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

using PUZZLEgestServer.DTO;
using System.Data.Objects.DataClasses;

namespace PUZZLEgestServer
{
    public static class Functions
    {

        /// <summary>
        /// Translates an entity object into a data transfer object (DTO) for serialization
        /// </summary>
        /// <param name="entObj"></param>
        /// <returns></returns>
        public static DTO.DTO EntityToDTO(EntityObject entObj)
        {

            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            formatter.Serialize(stream, entObj);


            //create instance of a new DTO object of the entityObject type.name type

            //http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx

            foreach (PropertyInfo pi in entObj.GetType().GetProperties())
            {
                if (pi.Name == "EntityKey" || pi.Name == "EntityState")
                    continue;

                if (pi.PropertyType.FullName.StartsWith("System.Data.Objects.DataClasses.EntityCollection"))
                {
                    bool b = pi.PropertyType.IsGenericType;
                    Type[] genTypes = pi.PropertyType.GetGenericArguments();

                    object entityColObject = pi.GetValue(entObj, null);
                    if (entityColObject != null)
                    {
                        object x = entityColObject.GetType().GetMethod("ToArray").Invoke(entObj, null);
                    }

                    var y = pi.GetValue(entObj, null);



                    System.Data.Objects.DataClasses.EntityCollection<EntityObject> o = (System.Data.Objects.DataClasses.EntityCollection<EntityObject>)pi.GetValue(entObj, null);
                    object arr = o.ToArray();
                }

            }
            
            return null;
        }

        /// <summary>
        /// Translated a DTO object back to an entity object.
        /// </summary>
        /// <param name="dtoObj"></param>
        /// <returns></returns>
        public static EntityObject DTOToEntity(DTO.DTO dtoObj)
        {
            return null;
        }


    }
}
